#!/bin/bash

## Copyright (c) 2013, PoiXson, Mattsoft
## <http://poixson.com/>
## <http://mattsoft.net/>
## 
## Permission to use, copy, modify, and/or distribute this software for any
## purpose with or without fee is hereby granted, provided that the above
## copyright notice and this permission notice appear in all copies.
## 
## THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
## WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
## MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
## ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
## WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
## ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
## OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.


if [ -n "$DEBUG" ]; then
	return
fi


trap ctrl_c INT
function ctrl_c() {
	newline
	echo "** Trapped CTRL-C"
	newline
	exit
}


# clear
export PXN_HOME="/files"
# export PXN_SCRIPTS="$(dirname "$(readlink -fn "$0")")"
export PXN_SCRIPTS=${PXN_HOME}"/scripts"
export PXN_BACKUPS=${PXN_HOME}"/Backups"
export PXN_WORKSPACE=${PXN_HOME}"/workspace"
export PXN_REPOMIRRORS=${PXN_WORKSPACE}"/mirrors"
source ${PXN_SCRIPTS}/aliases.sh


DEBUG=0
# parse arguments
for i in ${@}; do
	if [ $i = "debug" ]; then
		DEBUG=1
	fi
done
#debug mode
if [ $DEBUG -ne 0 ]; then
	echo "[ DEBUG Mode ]"
	# Print commands when executed
	set -x
	# Variables that are not set are errors
#	set -u
fi


function newline() {
	echo -ne "\n"
}


function title() {
	local i=$((${#1}+8))
	local j=$((${#1}+4))
	local c=${#}
	newline
	echo -n " "; eval "printf '*'%.0s {1..$i}"; echo
	echo -n " "; eval "printf '*'%.0s {1..$i}"; echo
	echo -n " **"; eval "printf ' '%.0s {1..$j}"; echo "**"
	for line in "${@}"; do
		echo " **  ${line}  **"
	done
	echo -n " **"; eval "printf ' '%.0s {1..$j}"; echo "**"
	echo -n " "; eval "printf '*'%.0s {1..$i}"; echo
	echo -n " "; eval "printf '*'%.0s {1..$i}"; echo
	newline
	newline
}


function sleepdot() {
	sleep 1;echo -n "."
	sleep 1;echo -n "."
	sleep 1;echo ""
}
function sleepdotdot() {
	sleep 2;echo -n " ."
	sleep 2;echo -n " ."
	sleep 2;echo -n " ."
	sleep 2;echo -n " ."
	sleep 2;echo ""
}


function create_lock {
	LOCK_NAME=${1}
	while true; do
		if [[ -e "$LOCK_NAME" ]]; then
			OLDPID=`cat $LOCK_NAME`
#			if [ "ps p $OLDPID" > /dev/null ]; then
#				return 1
#			fi
#			rm -v $LOCK_NAME
			echo -n "Script is already running."; sleepdotdot
		else
			# got lock
			echo $$ > $LOCK_NAME
			break
		fi
	done
	return 0
}
function remove_lock {
	LOCK_NAME=${1}
	rm -vf $LOCK_NAME
}

